<html>
<head>
<title>锁具注册</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<link rel="shortcut icon" href="resources/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="resources/css/stylemain.css">
<link rel="stylesheet" href="resources/layui/css/layui.css">

<link rel="stylesheet" href="resources/layui/css/treeTable.css">
<link rel="stylesheet" href="resources/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="resources/layui/layui.all.js"></script>
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/base64.js"></script>
<style type="text/css">
.layui-form-checkbox i {
    margin-top: 5px !important;
}

input[type=checkbox] {
        width:15px;
        height:15px; 
        text-align: center;
    }
    input[type=checkbox]:after {
        width: 100%;
        height: 100%;
        top: 0px;
        content: " ";
        background-color:White;
        color: #000000;
        display: inline-block;
        visibility: visible;
        border-radius: 2px;
        border:1px solid black;
    }
    input[type=checkbox][disabled=disabled]:after {
        width: 100%;
        height: 100%;
        top: 0;
        content: " ";
        background-color:#DCDCDC;
        color: #000000;
        display: inline-block;
        visibility: visible;
        border-radius: 2px;
        border:1px solid #A9A9A9;
    }
    input[type=checkbox]:checked:after {
        content: "\2713";/*UNICODE中对号*/
        font-size: 12px;
        font-weight:bold;
    }

#checkbox_low {
	display: inline-block;
	margin: 0 0 0 20;
	padding: 0;
	vertical-align: middle;
}
</style>

</head>
<body>

<div class="layui-form">
	<table style="margin-top:10px">
		<tr>
			<td>
				<button class="layui-btn layui-btn-sm" id="btn_import"><i class="layui-icon">&#xe67c;</i> 导入</button>
			</td>
			<td>
				<button class="layui-btn layui-btn-sm layui-btn-danger" style="margin-left:10px" onclick="u_remove()"><i class="fa fa-trash" aria-hidden="true"></i> 删除</button>
			</td>			
			<td>
				<label style="margin-left:10px">注册时间:</label><input type="text" id="c_start" placeholder="yyyy-MM-dd" class="table_bar_tool">-<input type="text" id="c_end" placeholder="yyyy-MM-dd" class="table_bar_tool">
			</td>
			<td>
				<label style="margin-left:10px">锁具识别码:</label>
			</td>
			<td>
				<input type="text" id="slocksn" placeholder="" autocomplete="off" class="layui-input" style="height:30px">
			</td>
			<td>
				<button class="layui-btn layui-btn-sm" onclick="doSearch()" style="margin-left:10px"><i class="layui-icon layui-icon-search"></i> 查询</button>
				<span id="checkbox_low"><input type="checkbox" id="disbelow" value="0" style="display:inline-block">    只显示未登记</input></span>
			</td>
		</tr>
	</table>
  	
  
</div>
<table class="layui-hide" id="tbl_lock" lay-filter="tbl_lock"></table>
<div id="page"></div>
<script type="text/javascript">
var table = layui.table;
var laypage = layui.laypage;
var laydate = layui.laydate;
var element = layui.element;
var upload = layui.upload;
var _currpage = 1;
var _pageSize = 20;
var _slocksn = "";
var start_date = "";
var end_date = "";
var curopt = "";
$("#c_start").blur(function(){
	laydate.render({
	    elem: '#c_start'
	    ,value: myparser($('#c_start').val())
	    ,format: 'yyyy-MM-dd'
	});
});

$("#c_end").blur(function(){
	laydate.render({
	    elem: '#c_end'
	    ,value: myparser($('#c_end').val())
	    ,format: 'yyyy-MM-dd'
	});
});

$('#disbelow').bind('click',function(event){
		getData(_currpage,_pageSize,$('#slocksn').val());
});

layui.use([], function(){
	var today = new Date();
	var strYear = today.getFullYear();
	var strDay = pad(today.getDate(), 2);
	var strMonth = pad(today.getMonth(), 2);
    //debugger;
    start_date = (strYear + '-' + strMonth + '-' + strDay);
    end_date =  dateFormat('YYYY-mm-dd',today);
	//初始赋值
	laydate.render({
	    elem: '#c_start'
	    ,value: start_date
	    ,format: 'yyyy-MM-dd'
	    ,isInitValue: true
	});
    laydate.render({
    	elem: '#c_end'
    	,value: end_date
    	,format: 'yyyy-MM-dd'
    	,isInitValue: true
    });
    
	var uploadInst = upload.render({
	    elem: '#btn_import' //绑定元素
	    ,url: 'upload.do' //上传接口
	    ,accept: 'file'
    	,before: function(obj){ 
    		curopt = "add";
    	    layer.load(1);
    	}
    	,done: function(res){
	      //上传完毕回调
	      	layer.closeAll();
	      	if(res.status == "1"){
	      		layer.msg("锁具注册成功!", {icon: 1,time: 2000});
	      		getData(_currpage,_pageSize,$('#slocksn').val());
	      	}else{
	      		layer.msg(res.desc, {icon: 2,time: 3000});
	      	}
	    	
	    }
	    ,error: function(){
	      	//请求异常回调
	      	layer.closeAll();
	    	layer.msg("文件上传异常!", {icon: 2,time: 3000});
	    }
	});
	getData(_currpage,_pageSize,"");

});


$('#ckpassword').on('keydown', function (event) {
    if (event.keyCode == 13) {
    	userckopt();
		layer.closeAll();
    }
});

function ckdialgo_auth(){
	layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "复核" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '260px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#dlgck")     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     //var mask = $(".layui-layer-shade");
			     //mask.appendTo(layero.parent());
			     $('#ckname').focus();
			     //其中：layero是弹层的DOM对象
			}
		 ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	userckopt();
	    		$("#dlgck").css('display','none');
			 	layer.close(index);
		    	
			 	 
		  }
		  ,btn2: function(index, layero){
		    	//按钮【按钮二】的回调
		    
		    	$("#dlgck").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    $("#dlgck").css('display','none'); 
			    
		 }
	});
}

function doSearch(){
	start_date = $('#c_start').val();
	end_date = $('#c_end').val();
	_currpage = 1;
	getData(_currpage,_pageSize,$('#slocksn').val());
}

function getData(pageNumber,pageSize,locksn){
	_slocksn = locksn;
	var ckflag = $('#disbelow').prop("checked") == true?1:0;
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"start":"' + start_date + '","end":"' + end_date + '","locksn":"' + _slocksn + '","flag":' + ckflag + '}';
	var layeri = layer.load(2);
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getlockreglist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			tablerender(msg);
			page(msg);
			layer.close(layeri);
		},
        error : function(e){
        	layer.close(layeri);
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
        }
	});
}

function tablerender(data){	
	table.render({
		  elem: '#tbl_lock'
		  ,cellMinWidth: 50
		  ,cols: [
			  [
				{type:'checkbox'}
		    ,{field:'locksn', title: '识别码', width:200} 
		    ,{field:'lockid', title: '内部编号'}
		    ,{field:'used', title: '已登记', width:100, align: 'center', templet: '#authTpl'}
		    ,{field:'optdate', title: '注册时间', width:200}		    
		  ]
			  ]
		  ,data:data.datalist
		  ,limit: data.pageSize
		  ,height: parent.iframeH - 110
		});	
}

function numpage(pageNumber, pageSize) {
	var ckflag = $('#disbelow').prop("checked") == true?1:0;
	var datastring = '{"pageNumber":'+pageNumber+',"pageSize":'+ pageSize + ',"start":"' + start_date + '","end":"' + end_date + '","locksn":"' + _slocksn + '","flag":' + ckflag + '}';
	var layeri = layer.load(2);
	//debugger;
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "getlockreglist",
		type : "post",
		data : datastring,
		dataType : "json",
		success : function(msg) {
			//debugger;
			tablerender(msg);
			layer.close(layeri);
		},
        error : function(e){
        	layer.close(layeri);
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
            
        }
	});
}

function page(data) {
    laypage.render({
        elem: 'page', //注意，这里的 page 是 ID，不用加 # 号
        count: data.totalCount, //数据总数，从服务端得到
        limit: data.pageSize,  // 每页条数
        limits: [10, 20, 30, 40, 50],
        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
        curr: _currpage,
        jump: function (obj, first) {
            //console.log(obj)
            //obj包含了当前分页的所有参数，比如：
            //layer.msg(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //console.log(obj.limit); //得到每页显示的条数

            //首次不执行
            if (!first) {
                //do something
                _currpage = obj.curr;
                _pageSize = obj.limit;
                numpage(obj.curr, obj.limit)  // 分页点击传参 
            }
        }
    });
}

function GetChecked(){
 	var checkedItems = table.checkStatus('tbl_lock');	
    var jsonstr = '{';
	 $.each(checkedItems.data, function(index, item){
		 if(item.used == "1"){
			 layer.msg("已登记的锁具无法删除!");
			 return "";
		 }
	     if(index != (checkedItems.data.length - 1)){
	    	 jsonstr += '"' +item.locksn + '":"' + item.locksn + '",';
	     }else{
	    	 jsonstr += '"' +item.locksn + '":"' + item.locksn + '"}';
	     }
	     
	 });   
	 
	return jsonstr;
}

function u_remove(ckname,ckpassword){	
	var checkedjson = GetChecked();
	if (checkedjson.length > 5){
		curopt = "del";
		var datastring = '{"rname":"智能锁管理/锁具管理/锁具注册","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'","children":' + checkedjson  + '}';
		if(ckname == ''){
			layer.confirm('确定要删除锁具?', {
				  btn: [ '确定','取消'] //可以无限个按钮				  
				}, function(index, layero){
				  //按钮【按钮一】的回调
				  $.ajax({
						type:"post",
						contentType: "application/json;charset=UTF-8",
						url: "lockrefdel",
						async:false,
						data:datastring,
				     	dataType:"json",
				        success: function(msg) {    //数据提交成功时返回数据
							if(msg.status == "1"){
								layer.closeAll();
								getData(_currpage,_pageSize,$('#slocksn').val());
							}else if(msg.status == "1211"){
								$('#ckname').val('');
								$('#ckpassword').val('');
								//debugger;
								ckdialgo_auth();
				        		
							}else{
								layer.msg(msg.desc);
							}						
							
				        },
				        error : function(e){
				        	if(e.status == 200){
				        		parent.location.href = "login";
				        	}else{
				        		alert(e.status);
				                alert(e.responseText);
				        	}
				        }

					});	
					
				}, function(index){
					layer.closeAll();
				});			
		}else{
			$.ajax({
				type:"post",
				contentType: "application/json;charset=UTF-8",
				url: "lockrefdel",
				async:false,
				data:datastring,
		     	dataType:"json",
		        success: function(msg) {    //数据提交成功时返回数据
					if(msg.status == "1"){
						getData(_currpage,_pageSize,$('#slocksn').val());
					}else if(msg.status == "1211"){
						$('#ckname').val('');
						$('#ckpassword').val('');
						ckdialgo_auth();
					}else{
						layer.msg(msg.desc);
					}						
					
		        },
		        error : function(e){
		        	if(e.status == 200){
		        		parent.location.href = "login";
		        	}else{
		        		alert(e.status);
		                alert(e.responseText);
		        	}
		        }

			});
		}
							
	}else{
		layer.msg('需选择锁具!');
	}							
}

function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "del"){
		u_remove(ckname,$.base64.encode(ckpassword));
	}		
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}

function dateFormat(fmt, date) {
	var ret;
    var opt = {
        "Y+": date.getFullYear().toString(),        
        "m+": (date.getMonth() + 1).toString(),     
        "d+": date.getDate().toString(),           
        "H+": date.getHours().toString(),          
        "M+": date.getMinutes().toString(),        
        "S+": date.getSeconds().toString()         
    };
    for (var k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : pad(opt[k], ret[1].length));
        };
    };
    return fmt;
}

function myparser(s){
	if (!s) return new Date();

	var y,m,d;
	var ss = (s.split('-'));
	if(ss.length > 1){
		y = parseInt(ss[0],10);
		m = parseInt(ss[1],10);
		d = parseInt(ss[2],10);
	}else{
		y = parseInt(ss[0].substring(0,4),10);
		m = parseInt(ss[0].substring(4,6),10);
		d = parseInt(ss[0].substring(6,8),10);
	}
	
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
		return new Date(y,m-1,d);
	} else {
		return new Date();
	}
}

function pad(num, n) {  
    var len = num.toString().length;  
    while(len < n) {  
        num = "0" + num;  
        len++;  
    }  
    return num;  
}
</script>

<script type="text/html" id="authTpl">
  {{#  if(d.used == '0'){ }}	
    <span>否</span>
  {{# }else if(d.used == '1') { }}	
    <span style="color: #45b8ad;">是</span>
  {{# } }}	    
</script>
</body>
</html>
